<template>
    <div id="notice-detail">
        <el-row class="card-box">
            <el-card class="form-box">
                <el-form :label-position="labePosition" label-width="127px" size="mini">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="通知规则名称:">
                                <el-input v-model="ruleForm.ruleName" style="width: 70%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <!-- <el-form-item label="通知面板:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    filterable
                                    collapse-tags
                                    style="width:100%"
                                    clearable
                                    v-model="ruleForm.noticePanel"
                                >
                                    <el-option
                                        v-for="item in noticePanelStorage" 
                                        :key="item.panelCode"
                                        :label="item.panelCode + ' ' + item.panelName"
                                        :value="item.panelCode"
                                    ></el-option>
                                </el-select>
                            </el-form-item> -->
                            <el-form-item label="通知模块:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    filterable
                                    collapse-tags
                                    style="width: 70%"
                                    clearable
                                    v-model="ruleForm.noticeModules"
                                    @change="changeNoticeModules"
                                >
                                    <el-option
                                        v-for="item in noticeModulesStorage"
                                        :key="item.moduleCode"
                                        :label="item.moduleCode + ' ' + item.moduleName"
                                        :value="item.moduleCode"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="通知条目:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    filterable
                                    collapse-tags
                                    clearable
                                    v-model="ruleForm.entryCode"
                                    style="width: 70%"
                                    @change="changeAccountControlValue(ruleForm.entryCode, 'dictKey')"
                                >
                                    <el-option
                                        v-for="item in entryStorage"
                                        :key="item.dictKey"
                                        :label="item.dictKey + ' ' + item.dictKeyName"
                                        :value="item.dictKey"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="触警类型:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    filterable
                                    collapse-tags
                                    style="width: 70%"
                                    clearable
                                    v-model="ruleForm.thresholdType"
                                >
                                    <el-option
                                        v-for="item in thresholdTypeStorage"
                                        :key="item.dictKey"
                                        :label="item.dictKey + ' ' + item.dictKeyName"
                                        :value="item.dictKey"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="通知次数上限:">
                                <template slot="label">
                                    <span>
                                        <el-tooltip>
                                            <div slot="content">{{ limitTimeTitle }}</div>
                                            <i class="el-icon-question"></i>
                                        </el-tooltip>
                                        通知次数上限：
                                    </span>
                                </template>
                                <el-input v-model="ruleForm.limitTimes" @input.native="onInput" style="width: 70%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="3">
                            <el-form-item label="启用状态:" class="left-label">
                                <el-switch v-model="ruleForm.status" active-value="0" inactive-value="1" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="通知产品:">
                                <!-- <RiskEntryInputs
                                    :showAll="true"
                                    :interfaceUrl="'/fundInfo/list/byUser/like?fundCodeOrName='"
                                    @set-entry-data="getAccountControlValue"
                                    :returnDatas="ruleForm.fundCode"
                                    :showDis="false"
                                    style="width: 70%"
                                /> -->
                                <el-tooltip :disabled="!(ruleForm.fundCode && ruleForm.fundCode.length)" effect="dark" placement="top-start">
                                    <ul slot="content" style="min-height: 18px; max-height: 200px; overflow: auto">
                                        <li :key="item" v-for="item in ruleForm.fundCode">
                                            {{ item + ' ' + ((fundStorage.find(i => i.fundCode === item) || {}).fundName || '选择全部') }}
                                        </li>
                                    </ul>
                                    <el-select
                                        placeholder="请选择"
                                        multiple
                                        filterable
                                        collapse-tags
                                        clearable
                                        v-model="ruleForm.fundCode"
                                        style="width: 70%"
                                        @change="handleFund"
                                    >
                                        <el-option label="-1 选择全部" value="-1" :disabled="isDisabledAll"></el-option>
                                        <el-option
                                            v-for="item in fundStorage"
                                            :key="item.fundCode"
                                            :label="item.fundCode + ' ' + item.fundName"
                                            :value="item.fundCode"
                                            :disabled="isDisabledOther || showDis"
                                        ></el-option>
                                    </el-select>
                                </el-tooltip>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="通知产品组:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    filterable
                                    collapse-tags
                                    clearable
                                    v-model="ruleForm.fundGroup"
                                    style="width: 70%"
                                    @change="handleChangeFundGroup"
                                >
                                    <el-option
                                        v-for="item in fundGroup"
                                        :key="item.fundGroupCode"
                                        :label="item.fundGroupCode + ' ' + item.fundGroupName"
                                        :value="item.fundGroupCode"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <!-- <el-form-item label="剔除角色:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    clearable
                                    filterable
                                    collapse-tags
                                    v-model="ruleForm.filterRoles"
                                    style="width:70%"
                                    @change="changeAccountControlValue(ruleForm.filterRoles, 'roleCode')"
                                >
                                    <el-option
                                        v-for="item in roleInfo"
                                        :key="item.roleCode"
                                        :label="item.roleCode + ' ' + item.roleName"
                                        :value="item.roleCode"
                                    ></el-option>
                                </el-select>
                            </el-form-item> -->
                            <el-form-item label="通知角色:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    clearable
                                    filterable
                                    collapse-tags
                                    v-model="ruleForm.roleCodes"
                                    style="width: 70%"
                                    @change="changeAccountControlValue(ruleForm.roleCodes, 'roleCode')"
                                >
                                    <el-option
                                        v-for="item in roleInfo"
                                        :key="item.roleCode"
                                        :label="item.roleCode + ' ' + item.roleName"
                                        :value="item.roleCode"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="通知用户:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    clearable
                                    filterable
                                    collapse-tags
                                    v-model="ruleForm.noticeUser"
                                    style="width: 70%"
                                    @change="handleNoticeUser"
                                >
                                    <el-option
                                        v-for="item in userStorage"
                                        :key="item.userCode"
                                        :label="item.userName + ' ' + item.userNickName"
                                        :value="item.userCode"
                                    >
                                        <span style="float: left">{{ item.userName + ' ' + item.userNickName }}</span>
                                        <el-tooltip placement="left">
                                            <div slot="content">{{ item.roleName.join(',') }}</div>
                                            <span class="select-text"> {{ item.roleName.join(',') }} </span>
                                        </el-tooltip>
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row style="z-index: 1">
                        <el-col :span="8">
                            <el-form-item label="正文发送列设置:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    filterable
                                    collapse-tags
                                    style="width: 70%"
                                    clearable
                                    v-model="ruleForm.columns"
                                >
                                    <el-option
                                        v-for="item in columnsStorage"
                                        :key="item.dictKey"
                                        :label="item.dictKeyName"
                                        :value="item.dictKey"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="抄送列表:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    filterable
                                    collapse-tags
                                    style="width: 70%; position: realtive"
                                    clearable
                                    v-model="ruleForm.cc"
                                    @change="changeAccountControlValue(ruleForm.cc, 'emailId')"
                                >
                                    <el-option
                                        v-for="item in userList"
                                        :key="item.emailId"
                                        :label="item.emailName + ' ' + item.emailAddress"
                                        :value="item.emailId"
                                    ></el-option>
                                </el-select>
                                <el-link type="primary" class="editBtn" @click="editSend">编辑</el-link>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="通知时间段:">
                                <!-- <div>
                                    <el-time-picker
                                        is-range
                                        v-model="ruleForm.times"
                                        range-separator="至"
                                        start-placeholder="开始时间"
                                        end-placeholder="结束时间"
                                        placeholder="选择时间范围"
                                        style="width:90%"
                                        @change="handleTime"
                                        value-format="HHmmss"
                                        format="HH:mm:ss"
                                    >
                                    </el-time-picker>
                                    <el-tooltip content="添加" placement="top">
                                        <i
                                            class="el-icon-plus"
                                            circle
                                            type="primary"
                                            size="mini"
                                            style="background:#409eff; color: white;padding:3px;border-radius: 10px;margin-left:5px"
                                            @click="carouselAddClick"
                                        >
                                        </i>
                                    </el-tooltip>    
                                </div> -->
                                <div v-for="(item, index) in ruleForm.noticeTimes" :key="index" :style="{ 'margin-top': index == 0 ? '0px' : '5px' }">
                                    <!-- <el-time-picker
                                        is-range
                                        v-model="item.times"
                                        range-separator="至"
                                        start-placeholder="开始时间"
                                        end-placeholder="结束时间"
                                        placeholder="选择时间范围"
                                        style="width:70%"
                                        @change="testingTime(index)"
                                        value-format="HHmmss"
                                        format="HH:mm:ss"
                                    >
                                    </el-time-picker> -->
                                    <el-time-picker
                                        v-model="item.times[0]"
                                        @change="testingTime(index, 'startTime')"
                                        :default-value="defaultTime"
                                        value-format="HHmmss"
                                        format="HH:mm:ss"
                                        placeholder="开始时间"
                                        style="width: 120px"
                                    >
                                    </el-time-picker>
                                    <span style="margin: 0 6px">至</span>
                                    <el-time-picker
                                        v-model="item.times[1]"
                                        @change="testingTime(index, 'endTime')"
                                        :default-value="defaultTime2"
                                        value-format="HHmmss"
                                        format="HH:mm:ss"
                                        placeholder="结束时间"
                                        style="width: 120px"
                                    >
                                    </el-time-picker>
                                    <template v-if="index == 0">
                                        <el-tooltip content="添加" placement="top">
                                            <i
                                                class="el-icon-plus"
                                                circle
                                                type="primary"
                                                size="mini"
                                                style="background: #409eff; color: white; padding: 3px; border-radius: 10px; margin-left: 5px"
                                                @click="carouselAddClick"
                                            >
                                            </i>
                                        </el-tooltip>
                                    </template>
                                    <template v-else>
                                        <el-tooltip content="删除" placement="top">
                                            <i
                                                class="el-icon-minus"
                                                circle
                                                type="primary"
                                                size="mini"
                                                style="background: #409eff; color: white; padding: 3px; border-radius: 10px; margin-left: 5px"
                                                @click="carouselDelClick(item, index)"
                                            >
                                            </i>
                                        </el-tooltip>
                                    </template>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row style="position: absolute; top: 210px; width: 50%; z-index: 99">
                        <el-col :span="16">
                            <el-form-item label="通知日期区间:">
                                <el-date-picker
                                    v-model="ruleForm.dates"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    style="width: 67%"
                                    @change="handleDate"
                                    value-format="yyyyMMdd"
                                    format="yyyy-MM-dd"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" style="margin-left: -10px">
                            <el-form-item label="通知类型:">
                                <el-select placeholder="请选择" style="width: calc(190% + 10px)" v-model="ruleForm.noticeType">
                                    <el-option
                                        v-for="item in noticeTypeStorage"
                                        :key="item.dictKey"
                                        :label="item.dictKey + ' ' + item.dictKeyName"
                                        :value="item.dictKey"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
        </el-row>
        <el-row class="card-box">
            <el-card>
                <el-row>
                    <div class="link-box" v-if="isShowSubmit">
                        <el-link icon="el-icon-edit" v-show="!isEdit" @click="handleEdit">编辑</el-link>
                        <el-link icon="el-icon-view" v-show="isEdit" @click="handleEdit">预览</el-link>
                    </div>
                </el-row>
                <el-row class="email-title">
                    <h2 v-show="!isEdit">{{ ruleForm.greeting }}</h2>
                    <div v-show="isEdit" class="title-ipt">
                        <el-input v-model="ruleForm.greeting"></el-input>
                    </div>
                </el-row>
                <el-row style="margin-bottom: 10px">
                    <div v-show="!isEdit" class="text-box">{{ ruleForm.mainBody }}</div>
                    <el-input v-show="isEdit" type="textarea" autosize placeholder="请输入内容" v-model="ruleForm.mainBody"> </el-input>
                </el-row>
                <el-row>
                    <el-table ref="emailTable" :data="emailTable" border size="mini" style="width: 100%" height="calc(100vh - 665px)">
                        <el-table-column v-for="i in emailTableColumns" :prop="i.dictKey" :key="i.dictKey" :label="i.dictKeyName" min-width="100">
                        </el-table-column>
                    </el-table>
                </el-row>
                <el-row style="margin-top: 10px">
                    <div v-show="!isEdit" class="text-box">{{ ruleForm.subContent }}</div>
                    <el-input v-show="isEdit" type="textarea" autosize placeholder="" v-model="ruleForm.subContent"> </el-input>
                </el-row>
            </el-card>
        </el-row>
        <el-row class="card-box">
            <el-card>
                <div class="btns">
                    <el-button @click="$emit('close-tab', data.title)">取消</el-button>
                    <el-button v-if="isShowSubmit" type="primary" @click="submit" :loading="btnLoading">确认</el-button>
                </div>
            </el-card>
        </el-row>
        <template>
            <!-- 编辑抄送列表弹窗 -->
            <ClistPopup :editDivisible="editDivisible" @emitEditDivisible="emitEditDivisible"></ClistPopup>
        </template>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import RiskEntryInputs from '@/common/components/risk-entry-inputs.vue';
import { sortBy, uniqueFunc, changeOptions, PrefixInteger } from '@/utils/tools';
import ClistPopup from './components/clist-popup.vue';
import * as moment from 'moment';

@Component({
    name: 'WarningNoticeDetail',
    components: {
        RiskEntryInputs,
        ClistPopup,
    },
})
export default class WarningNoticeDetail extends Vue {
    @Prop() data: any;

    private labePosition: string = 'right';

    private ruleForm = {
        ruleName: '',
        // noticePanel: '',
        noticeModules: '',
        noticeType: '0',
        thresholdType: '',
        limitTimes: null,
        dates: [],
        startDate: '',
        endDate: '',
        fundCode: [],
        fundGroup: [],
        times: null,
        startTime: '',
        endTime: '',
        noticeUser: [],
        columns: [],
        status: '0',
        greeting: '风险监控屏通知',
        mainBody: '尊敬的领导：\n 您好！\n 根据风控系统实时监控告警，以下指标达预设提示范围，请及时关注！',
        subContent: '',
        noticeTimes: [
            {
                // startTime: '',
                // endTime: '',
                times: ['', ''],
                orderNum: null,
            },
        ],
        cc: [],
        filterRoles: [],
        entryCode: [],
        roleCodes: [], // 通知角色
    };

    private noticePanelStorage: any[] = [];

    private noticeModulesStorage: any[] = [];

    private thresholdTypeStorage: any[] = [];

    private noticeTypeStorage: any[] = [{ dictKey: '0', dictKeyName: '风险监控屏通知' }];

    private fundGroup: any[] = [];

    private userStorage: any[] = [];

    private showType: string = 'add';

    private btnLoading: boolean = false;

    private columnsStorage: any[] = [];
    private columnsObj = {};

    private userList = []; // 抄送列表

    private roleInfo = []; // 剔除角色

    private emailTable: any[] = [
        {
            entryCode: '',
            entryName: '',
            thresholdValue: '',
            fundName: '',
            calculateValue: '',
            calculateLogic: '',
            stockCode: '',
            stockName: '',
            remark: '',
            handleUser: '',
        },
    ];

    private isEdit: boolean = false; // 文本是否在编辑状态
    private editDivisible: boolean = false; // 抄送人编辑弹窗

    // 邮件发送列排序对象
    private columnSortPojo = {
        entryCode: 0, // 条目编号
        entryName: 1, // 条目名称
        thresholdValue: 2, // 阈值
        thresholdType: 3, // 触警状态
        fundName: 4, // 产品名称
        calculateValue: 5, // 实际值
        calculateLogic: 6, // 计算公式
        stockCode: 7, // 证券代码(名称)
        remark: 8, // 备注信息
        handleUser: 9, // 处理人
    };

    // // 轮询时间段
    // carouselTimes: any[] = [
    //     {
    //         times: null,
    //     },
    // ];

    NumLength = 0;
    defaultTime: any = new Date(0, 0, 0, moment().hour(), 0, 0);
    defaultTime2: any = new Date(0, 0, 0, moment().hour() + 1, 0, 0);
    limitTimeTitle: string = window.project_config.LIMIT_TIMES_TITLE || '该字段为在设置时间段内发送次数上限，非重复发送邮件次数';

    entryStorage: any[] = [];
    fundStorage: any[] = [];

    async mounted() {
        const docking =
            process.env.ENV_CONFIG === 'project' ? window.project_config.webDocking || window.project_config.WEB_DOCKING : process.env.WEB_DOCKING;

        if (docking === 'MAXWEALTH' && this.data.type === 'add') {
            this.ruleForm.mainBody =
                '尊敬的领导：\n    您好！\n    根据风控系统实时监控告警，以下指标触发告警提醒，具体指标明细可登陆系统进行查询https://risk.maxwealthfund.com \n    请及时处理并在指标完成调整前持续关注，谢谢！';
        }
        // 通知面板下拉框
        // this.getNoticePanelList();
        this.getNoticeModulesList();
        // 用户列表
        await this.getUserList();

        if (this.data.type === 'edit') {
            this.$axios
                .post('/role/user/query', {
                    fundCodes: this.ruleForm.fundCode || [],
                    fundGroupCodes: this.ruleForm.fundGroup,
                    filterRoles: this.ruleForm.filterRoles,
                    roleCodes: this.ruleForm.roleCodes,
                })
                .then((res: any) => {
                    let result = res.filter(key => {
                        const index = this.userStorage.findIndex(
                            item => item.userCode == key && item.userName != 'administrator' && item.userEnable === '1'
                        );
                        return index > -1;
                    });
                    // 手动的 = 已选的 - result
                    this.actionUserKeys = this.getSame(this.ruleForm.noticeUser, result);
                    console.log(result, 'result');
                    console.log(this.ruleForm.noticeUser, 'this.ruleForm.noticeUser');

                    console.log('编辑时: 我计算获取到的手动key', this.actionUserKeys);
                });

            this.$axios.post('/entry/subscribe/fund/module', { noticeModules: [], fundGroup: this.ruleForm.fundGroup }).then((res: any) => {
                // 手动的 = 已选的 - result
                this.actionFundKeys = this.getSame(this.ruleForm.fundCode, res);
                console.log(res, 'result');
                console.log(this.ruleForm.fundCode, 'this.ruleForm.fundCode');

                console.log('编辑时: 我计算获取到的手动key', this.actionFundKeys);
            });
        }
        // 条目列表
        if (this.ruleForm.noticeModules.length) {
            this.$axios.post('/entry/subscribe/entrys/list', this.ruleForm.noticeModules).then((res: any) => {
                // this.ruleForm.entryCode = res.map(item => item.dictKey) || [];
                this.entryStorage = res || [];
                this.changeAccountControlValue(this.ruleForm.entryCode, 'dictKey');
            });
        }
        // 获取剔除角色数据
        this.getRoleInfo();
        // 账户组
        this.getFundGroupList();
        // 抄送列表
        this.getMailCcList();
        // 触警类型下拉框
        this.thresholdTypeStorage = await SGU_CACHE('ThresholdType', '/dict/list/code/Y_000039', []);
        // 邮件通知类型
        // this.noticeTypeStorage = await SGU_CACHE('NoticeType', '/dict/list/code/Y_000266', []);
        // 邮件表格列下拉框
        this.columnsStorage = await SGU_CACHE('Columns', '/dict/list/code/Y_000273', []);
        this.columnsStorage.forEach(ele => {
            ele.sortNo = this.columnSortPojo[ele.dictKey];
        });
        this.columnsStorage = this.columnsStorage.sort(sortBy('sortNo', 'asc'));
        this.columnsObj = DictionConstUtil.ListToPojo(this.columnsStorage);

        if (this.data.type.indexOf('add') > -1) {
            this.ruleForm.columns = this.columnsStorage.map(i => i.dictKey);
        }

        // 条目数据
        this.fundStorage = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like', []);
        this.changeAccountControlValue(this.ruleForm.fundCode, 'fundCode');
    }

    // 监听父组件带进来的基础数据
    @Watch('data', { immediate: true, deep: true })
    async watchData(newData) {
        if (newData) {
            if (newData.content) {
                let data = JSON.parse(JSON.stringify(newData.content));
                data.dates = [String(...(data.startDate || '')), String(...(data.endDate || ''))];
                if (data.startTime) {
                    data.times = [PrefixInteger(data.startTime, 6), PrefixInteger(data.endTime, 6)];
                    // data.times = [data.startTime, data.endTime];
                } else {
                    data.times = ['', ''];
                }
                this.ruleForm = data ?? this.ruleForm;
                if (newData.content.noticeTimes.length != 0) {
                    let carouselTimes = [];
                    let Num = [];
                    newData.content.noticeTimes.forEach(item => {
                        carouselTimes.push({
                            times: [PrefixInteger(String(item.startTime), 6), PrefixInteger(String(item.endTime), 6)],
                            // times: [String(item.startTime), String(item.endTime)],
                            orderNum: item.orderNum,
                        });
                        Num.push(item.orderNum);
                    });
                    this.NumLength = Math.max.apply(null, Num);
                    this.ruleForm.noticeTimes = carouselTimes;
                } else {
                    this.ruleForm.noticeTimes = [{ times: ['', ''], orderNum: null }];
                    this.NumLength = 0;
                }
                if (this.ruleForm.fundGroup && this.ruleForm.fundGroup.length) {
                    this.ruleForm.fundCode = await (this.getNewFundCode(this.ruleForm.fundCode, this.ruleForm.fundGroup) as any);
                }
            }
            this.showType = newData.type;
        }
    }

    // 取a1不在a2里面的元素
    getSame(arr1, arr2) {
        return [...new Set(arr1)].filter(item => !arr2.includes(item));
    }

    // @Watch('ruleForm.fundCode', { immediate: false, deep: true })
    // onWatchFundCode(val1, val2) {
    //     if (val1 != val2 || (val2 && val2.length == 0)) {
    //         this.changeByFund();
    //     }
    // }

    get emailTableColumns() {
        let columns = [];
        for (let i = 0; i < this.ruleForm.columns?.length; i++) {
            const element = this.ruleForm.columns[i];
            if (this.columnsStorage.length) {
                let obj = this.columnsStorage.find(item => item.dictKey === element);
                if (obj) {
                    columns.push(obj);
                }
            }
        }
        columns.forEach(ele => {
            ele.sortNo = this.columnSortPojo[ele.dictKey];
        });
        columns = columns.sort(sortBy('sortNo', 'asc'));
        return columns;
    }

    get isShowSubmit() {
        return ['add', 'edit'].includes(this.showType);
    }

    private getNoticePanelList() {
        this.$axios.get('/entry/subscribe/all/panel/user').then((res: any) => {
            this.noticePanelStorage = res;
        });
    }

    private getNoticeModulesList() {
        this.$axios.get('/entry/subscribe/all/module/user').then((res: any) => {
            this.noticeModulesStorage = res;
        });
    }

    // 获取列表
    private getMailCcList() {
        this.$axios
            .post('/notice/monitor/rule/mailCc/list', {
                emailId: '',
                emailName: '',
                emailAddress: '',
            })
            .then((res: any) => {
                if (res) {
                    this.userList = [];
                    let cc = [];
                    res.list.forEach(item => {
                        this.userList.push(item);
                        if (this.ruleForm.cc.length != 0) {
                            if (this.ruleForm.cc.includes(item.emailId)) {
                                cc.push(item.emailId);
                            }
                        }
                    });
                    if (this.ruleForm.cc.length != 0) {
                        this.ruleForm.cc = cc;
                    }
                }
            });
    }

    getUserList() {
        return new Promise((resolve, reject) => {
            this.$axios
                .get('/userManage/user/list')
                .then((res: any) => {
                    if (res) {
                        res.forEach(element => (element.sortId = element.roleCodes?.[0] || '0'));
                        res.sort((a, b) => Number(b.sortId.replace('YH', '')) - Number(a.sortId.replace('YH', '')));

                        this.userStorage = res.filter(item => item.userName != 'administrator' && item.userEnable === '1');
                    }
                    this.changeAccountControlValue(this.ruleForm.noticeUser, 'userCode');
                    resolve(res);
                })
                .catch(error => {
                    reject(error);
                });
        });
    }

    // 获取账户组数据
    private getFundGroupList(): void {
        // 传false,默认展示全部，不传（默认true），会排除掉导出类型为不导出的那些外部产品组
        this.$axios.post('/fundGroup/list').then((res: any) => {
            this.fundGroup = res;
        });
    }
    // 通知模板改变获取产品编码
    private changeNoticeModules(val: string[]) {
        this.changeAccountControlValue(this.ruleForm.noticeModules, 'moduleCode');
        this.ruleForm.fundGroup = [];
        this.$axios.post('/entry/subscribe/fund/module', { noticeModules: val, fundGroup: this.ruleForm.fundGroup }).then((res: any) => {
            this.ruleForm.fundCode = res;
            // this.ruleForm.fundCode = [...new Set([...this.actionFundKeys, ...res])];
            // if (this.ruleForm.fundCode.includes('-1')) {
            //     this.ruleForm.fundCode = ['-1'];
            // }
            // this.systemFundKeys = res;
            this.changeAccountControlValue(this.ruleForm.fundCode, 'fundCode');
        });
        this.$axios.post('/entry/subscribe/entrys/list', val).then((res: any) => {
            this.ruleForm.entryCode = res.map(item => item.dictKey) || [];
            this.entryStorage = res || [];
            this.changeAccountControlValue(this.ruleForm.entryCode, 'dictKey');
        });
    }

    /**
     * 产品组变动事件
     * @param {string[]} val 选中值
     */
    handleChangeFundGroup(val: string[]): void {
        this.changeAccountControlValue(this.ruleForm.fundGroup, 'fundGroupCode');

        if (this.ruleForm.noticeModules.length && this.ruleForm.fundCode.length && this.ruleForm.fundCode.indexOf('-1') > -1) {
            return;
        }
        this.$axios.post('/entry/subscribe/fund/module', { noticeModules: [], fundGroup: val }).then((res: any) => {
            // this.ruleForm.fundCode = res;
            // this.changeAccountControlValue(this.ruleForm.fundCode, 'fundCode');
            this.ruleForm.fundCode = [...new Set([...this.actionFundKeys, ...res])];
            if (this.ruleForm.fundCode.includes('-1')) {
                this.ruleForm.fundCode = ['-1'];
            }
            this.systemFundKeys = res;
            this.changeAccountControlValue(this.ruleForm.fundCode, 'fundCode');
        });
    }

    /**
     * 回显重新请求获取最新的产品 不使用row数据中的fundCode
     */
    getNewFundCode(fundCode, fundGroup) {
        return new Promise<void>((resolve, reject) => {
            this.$axios
                .post('/entry/subscribe/fund/module', { fundCode, fundGroup })
                .then((res: any) => {
                    resolve(res);
                })
                .catch(error => {
                    reject(error);
                });
        });
    }

    // 获取通知用户
    private changeByFund() {
        this.$axios
            .post('/role/user/query', {
                fundCodes: this.ruleForm.fundCode || [],
                fundGroupCodes: this.ruleForm.fundGroup,
                filterRoles: this.ruleForm.filterRoles,
                roleCodes: this.ruleForm.roleCodes,
            })
            .then((res: any) => {
                let result = res.filter(key => {
                    const index = this.userStorage.findIndex(
                        item => item.userCode == key && item.userName != 'administrator' && item.userEnable === '1'
                    );
                    return index > -1;
                });
                console.log('this.actionUserKeys 手动的', this.actionUserKeys);
                console.log('result 系统的', result);

                this.ruleForm.noticeUser = [...new Set([...this.actionUserKeys, ...result])];
                this.systemUserKeys = result;
                this.changeAccountControlValue(this.ruleForm.noticeUser, 'userCode');
            });
    }

    // 获取通知角色数据
    private getRoleInfo(): void {
        this.$axios.get('/role/query/all').then((res: any) => {
            console.log('resres11', res);
            this.roleInfo = [];
            for (let item of res) {
                if (item.sourceType === '1') {
                    this.roleInfo.push(item);
                }
            }
        });
    }

    private handleDate(val: any) {
        if (val && val.length) {
            this.ruleForm.startDate = val[0];
            this.ruleForm.endDate = val[1];
            return;
        }
        this.ruleForm.startDate = '';
        this.ruleForm.endDate = '';
    }

    // private handleTime(val: any) {
    //     if (val && val.length) {
    //         this.ruleForm.startTime = val[0];
    //         this.ruleForm.endTime = val[1];
    //         return;
    //     }
    //     this.ruleForm.startTime = '';
    //     this.ruleForm.endTime = '';
    // }
    // 判断时间是否存在交叉
    private testingTime(val, field?: string) {
        const times = this.ruleForm.noticeTimes[val].times;
        if (times[0] && times[1]) {
            if (times[0] > times[1]) {
                this.yh_message_warn('开始时间不得晚于结束时间!');
                this.ruleForm.noticeTimes[val].times = ['', ''];
                return;
            }
        }
        for (let i = 0; i < this.ruleForm.noticeTimes.length; i++) {
            for (let j = 0; j < this.ruleForm.noticeTimes.length; j++) {
                if (this.ruleForm.noticeTimes[i].times && this.ruleForm.noticeTimes[j].times) {
                    if (j != i) {
                        if (
                            moment(this.ruleForm.noticeTimes[i].times[0], 'HHmmss').isBetween(
                                moment(this.ruleForm.noticeTimes[j].times[0], 'HHmmss'),
                                moment(moment(this.ruleForm.noticeTimes[j].times[1], 'HHmmss'))
                            ) ||
                            moment(this.ruleForm.noticeTimes[i].times[1], 'HHmmss').isBetween(
                                moment(this.ruleForm.noticeTimes[j].times[0], 'HHmmss'),
                                moment(moment(this.ruleForm.noticeTimes[j].times[1], 'HHmmss'))
                            )
                        ) {
                            this.yh_message_warn('通知时间段不可交叉!');
                            if (val == this.ruleForm.noticeTimes.length - 1) {
                                this.ruleForm.noticeTimes[this.ruleForm.noticeTimes.length - 1].times = ['', ''];
                            } else {
                                this.ruleForm.noticeTimes[val].times = ['', ''];
                            }
                            return;
                        }
                    }
                }
            }
        }
    }

    private getAccountControlValue(val: any) {
        this.$set(this.ruleForm, 'fundCode', val);
    }

    private submit() {
        if (!this.verify()) {
            return;
        }
        this.btnLoading = true;

        let urlType = {
            add: '/notice/monitor/rule/add',
            edit: '/notice/monitor/rule/update',
        };
        let url = urlType[this.showType];
        let Time = [];
        let ruleForm = JSON.parse(JSON.stringify(this.ruleForm));

        ruleForm.noticeTimes.forEach((item, index) => {
            if (item.times[0] && item.times[1]) {
                if (item.orderNum) {
                    Time.push({
                        startTime: item.times[0],
                        endTime: item.times[1],
                        orderNum: item.orderNum,
                    });
                } else {
                    this.NumLength += 1;
                    Time.push({
                        startTime: item.times[0],
                        endTime: item.times[1],
                        orderNum: this.NumLength,
                    });
                }
            } else {
                ruleForm.noticeTimes.splice(index, 1);
            }
        });
        ruleForm.noticeTimes = Time;

        ruleForm.limitTimes = ruleForm.limitTimes ? Number(ruleForm.limitTimes) : null;

        // this.ruleForm.limitTimes = this.ruleForm.limitTimes || null;

        // return
        this.$axios({ url, method: 'post', data: ruleForm })
            .then((res: any) => {
                this.btnLoading = false;
                this.yh_message_success('操作成功！');
                this.$emit('close-tab', this.data.title);
            })
            .catch(() => {
                this.btnLoading = false;
            });
    }

    private verify() {
        if (!this.ruleForm.ruleName) {
            this.yh_message_warn('规则名称不能为空！');
            return false;
        }
        if (!this.ruleForm.noticeUser.length) {
            this.yh_message_warn('通知用户不能为空！');
            return false;
        }
        if (!this.ruleForm.thresholdType.length) {
            this.yh_message_warn('触警类型不能为空！');
            return false;
        }
        // let reg = /^[1-9]\d*$/g;
        // if (!reg.test(this.ruleForm.limitTimes)) {
        //     this.$message({ type: 'warning', message: '通知次数上限不能小于1！' });
        //     return false;
        // }
        if (!this.ruleForm.columns.length) {
            this.yh_message_warn('正文发送列不能为空！');
            return false;
        }

        return true;
    }

    // 获取条目列表
    private getEntryList(): void {
        this.$axios
            .post('/entry/list/CodeOrName', {
                codeOrName: '',
                entryType: '',
                paging: { currentPage: 1, pageSize: 19960831 },
                filterEntryCode: [],
            })
            .then((res: any) => {
                this.entryStorage = res.list;
            });
    }

    private handleEdit() {
        this.isEdit = !this.isEdit;
    }

    private onInput(e) {
        e.target.value = e.target.value.replace(/[^0-9]/g, '');
    }

    private editSend() {
        this.editDivisible = true;
    }

    private emitEditDivisible(param) {
        this.editDivisible = param;
        this.getMailCcList();
    }
    // 添加通知时间段
    private carouselAddClick() {
        this.ruleForm.noticeTimes.push({
            times: ['', ''],
            orderNum: null,
        });
    }
    // 通知时间段删除
    private carouselDelClick(param1, param2) {
        this.ruleForm.noticeTimes.splice(param2, 1);
    }
    // 下拉框数据置顶
    private changeAccountControlValue(val: any = [], field): void {
        let arr = [];
        if (val.some(item => item === '-1')) {
            arr.push({ label: '选择全部' });
        } else {
            if (field === 'roleCode') {
                this.changeByFund();
            }
        }

        // 下拉框选中数据置顶
        if (field == 'fundGroupCode') {
            this.fundGroup = changeOptions(val, this.fundGroup, field);
        } else if (field == 'userCode') {
            // this.userStorage = changeOptions(val, this.userStorage, field);
            this.userStorage = this.sortCheckOptions(val, this.userStorage, field);
        } else if (field == 'moduleCode') {
            this.noticeModulesStorage = changeOptions(val, this.noticeModulesStorage, field);
        } else if (field == 'emailId') {
            this.userList = changeOptions(val, this.userList, field);
        } else if (field == 'roleCode') {
            this.roleInfo = changeOptions(val, this.roleInfo, field);
        } else if (field == 'dictKey') {
            this.entryStorage = changeOptions(val, this.entryStorage, field);
        } else if (field == 'fundCode') {
            if (!val || (val && !val.length)) {
                this.isDisabledAll = false;
                this.isDisabledOther = false;
            } else {
                if (val.includes('-1')) {
                    this.isDisabledAll = false;
                    this.isDisabledOther = true;
                } else {
                    this.isDisabledAll = true;
                    this.isDisabledOther = false;
                }
            }
            this.fundStorage = changeOptions(val, this.fundStorage, field);
        }
    }

    isDisabledAll: boolean = false; // 全部选择是否禁用

    isDisabledOther: boolean = false; // 其他选择是否禁用

    /**
     * 获取下拉数据 根据已选择数据排序
     * @param selectedData 已选择的数据
     * @param optionsData 所有选项数据
     * @param key 排序的键值
     * @returns 排序后的结果数组
     */
    sortCheckOptions(selectedData: any[], optionsData: any[], key: string): any[] {
        const selectedOptions = selectedData.map(item => optionsData.find(option => item === option[key])).filter(Boolean);
        // 将已选中项进行排序 (根据角色[0]排在一起)
        selectedOptions.sort((a, b) => Number(b.sortId.replace('YH', '')) - Number(a.sortId.replace('YH', '')));
        const otherOptions = optionsData.filter(option => !selectedOptions.includes(option));
        const sortedOptions = [...selectedOptions, ...otherOptions];

        const map = new Map();
        for (const item of sortedOptions) {
            if (!map.has(item[key])) {
                map.set(item[key], item);
            }
        }
        const newArr = [...map.values()];
        return newArr;

        // return [...new Set(sortedOptions.map(option => option[key]))].map(key => sortedOptions.find(option => option[key] === key));
    }

    actionUserKeys: any[] = [];
    systemUserKeys: string[] = [];
    /**
     * 用户手动勾选事件
     */
    handleNoticeUser(val) {
        // if (!this.actionUserKeys.length) {
        // this.actionUserKeys = val;
        // } else {
        this.actionUserKeys = val.filter(item => !this.systemUserKeys.includes(item));
        // }

        this.changeAccountControlValue(this.ruleForm.noticeUser, 'userCode');
    }

    actionFundKeys: any[] = [];
    systemFundKeys: string[] = [];
    /**
     *  产品手动勾选事件
     */
    handleFund(val) {
        console.log('产品手动勾选事件触发--当前选中值:', val);

        this.actionFundKeys = val.filter(item => !this.systemFundKeys.includes(item));
        this.changeAccountControlValue(this.ruleForm.fundCode, 'fundCode');
    }
}
</script>
<style lang="scss" scoped>
#notice-detail {
    .card-box {
        margin-bottom: 10px;
        .form-box {
            min-height: 270px;
            .left-label {
                /deep/ .el-form-item__label {
                    width: 80px !important;
                }
                /deep/ .el-form-item__content {
                    margin-left: 80px !important;
                }
            }
            /deep/ .el-form-item__label {
                color: black;
            }
            /deep/ .el-date-editor .el-range-separator {
                padding: 0 15px;
            }
        }
        .email-title {
            margin-bottom: 20px;
            h2 {
                text-align: center;
                font-size: 1.5em;
            }
            .title-ipt {
                width: 200px;
                margin: 0 auto;
                /deep/ .el-input__inner {
                    font-size: 1.5em;
                }
            }
        }
        .text-box {
            font-family: monospace;
            font-size: inherit;
            white-space: pre-wrap;
        }
        .link-box {
            float: right;
            padding-right: 10px;
            /deep/ .el-link {
                margin: 0 5px;
            }
        }
        .btns {
            display: inline;
            float: right;
            padding-bottom: 20px;
        }
    }
}
.editBtn {
    position: absolute;
    right: 15%;
    color: #409eff;
}
/deep/ .el-select__tags-text {
    display: inline-block;
    max-width: 70px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
/deep/ .el-tag__close.el-icon-close {
    top: -5px;
}

.select-text {
    float: right;
    color: #8492a6;
    font-size: 13px;
    padding-right: 20px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 330px;
}
</style>
